package com.aifast.system.util;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.spring.SpringMVCUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.aifast.common.cache.util.RedisUtil;
import com.aifast.common.global.BusinessException;
import com.aifast.common.global.Const;
import com.aifast.system.sys.entity.UserInfo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author fujian
 * @since 2022/11/17 15:37
 * 自定义用户工具类
 */
public class UserUtil {

    /**
     * 获取satoken格式的缓存key
     * @param value token
     * @return
     */
    public static String getSaTokenKey(String value){
        return StrUtil.join(Const.SYMBOL_COLON,Const.TOKEN_HEADER,"login","token",value);
    }

    /**
     * 获取aifast 项目缓存用户信息的key
     * @param userId 用户id
     * @return
     */
    public static String getUserCacheKey(String userId){
        return StrUtil.join(Const.SYMBOL_COLON,Const.AUTH_PREFIX,userId);
    }

    /**
     * 根据sa token的缓存key获取用户id
     * @param key satoken缓存key
     * @return
     */
    public static String getUserId(String key){
        if(!RedisUtil.exists(key))return null;
        return RedisUtil.get(key);
    }

    /**
     * 获取当前用户信息封装类
     * @return UserInfo
     */
    public static UserInfo get(){
        String headerValue = SpringMVCUtil.getRequest().getHeader(Const.TOKEN_HEADER);
//        Console.log("value=>" + headerValue.substring(7));
        Opt.ofNullable(headerValue).orElseThrow(BusinessException::new,NotLoginException.DEFAULT_MESSAGE);
        String userId = getUserId(getSaTokenKey(headerValue.substring(7)));
        return get(userId);
    }

    /**
     * 获取当前用户信息封装类
     * @param request
     * @return UserInfo
     */
    public static UserInfo get(HttpServletRequest request){
        String headerValue = request.getHeader(Const.TOKEN_HEADER);
        String userId = getUserId(getSaTokenKey(headerValue.substring(7)));
        return get(userId);
    }

    /**
     * 获取当前用户信息封装类
     * @return UserInfo
     */
    public static UserInfo get(Object userId){
        String userCacheKey = getUserCacheKey(userId.toString());
        if(!RedisUtil.exists(userCacheKey))throw new BusinessException(NotLoginException.TOKEN_TIMEOUT_MESSAGE);
        return JSONUtil.toBean(RedisUtil.get(userCacheKey),UserInfo.class);
    }


}
